<div id="user_rapoarte_facturi_neincasate"></div>

<script type="text/javascript">	
		
Ext.onReady(function(){	
	
	var ds_facturi_neincasate;
	var cm_facturi_neincasate;
	var grid_user_rapoarte_facturi_neincasate;	
	var fp_w_user_rapoarte_facturi_emise_incasare;
	var w_user_rapoarte_facturi_emise_incasare;
	
	function getExcel() {

        if (!Ext.fly('tbExcel')) {
            return {
                xtype: 'tbbutton',
                id: 'tbExcel',
				text:'Excel',
				tooltip:'Exporta in excel',
				iconCls:'b_excel_cls',
                handler: function() {
                    //create dummy form
                    if (!Ext.fly('frmDummy')) {
                        var frm = document.createElement('form');
                        frm.id = 'frmDummy';
                        frm.name = id;
                        frm.className = 'x-hidden';
                        document.body.appendChild(frm);
                    }
                    //get attachment
						Ext.Ajax.request({
						   url: 'user/functionalitati/excel/' + Math.random(),
						   disableCaching	:false,
						   isUpload			:true,
						   params:{
								saferequest	:true,
								table		:'facturi_neincasate',
								filename	: 'raport',
								cyDep		:true,	
								active		:false,
								start 		:grid_user_rapoarte_facturi_neincasate.store.lastOptions.params.start,
								limit		:grid_user_rapoarte_facturi_neincasate.store.lastOptions.params.limit,
								sort		:grid_user_rapoarte_facturi_neincasate.store.lastOptions.params.sort,
								dir			:grid_user_rapoarte_facturi_neincasate.store.lastOptions.params.dir,
								fields		:grid_user_rapoarte_facturi_neincasate.store.lastOptions.params.fields,
								query		:grid_user_rapoarte_facturi_neincasate.store.lastOptions.params.query																	   	
						   },
                        form: Ext.fly('frmDummy')
                    });
                }
            };

        } else {
            return Ext.getCmp('tbExcel');
        }
    }
	
	function facturi_pay(){
			if(grid_user_rapoarte_facturi_neincasate.selModel.getCount() == 1){
				Ext.MessageBox.confirm('Confirmation','Adaugare incasare. Continuati?', function(btn){
					if (btn == 'yes') {			
						if (!w_user_rapoarte_facturi_emise_incasare) {
									// adaugare incasare form panel	-----------------------------------------------------
									//-----------------------------------------------------------------------------------	
			
									fp_w_user_rapoarte_facturi_emise_incasare = new Ext.FormPanel({
												id			:"add-incasare-form",
												monitorValid:true,
												labelAlign	:'top',
												bodyStyle	:'padding:5px',
										        layout		:'column',
										        border		:false,								
												items: [{
												            columnWidth:0.5,
															defaultType: 'textfield',
												            layout: 'form',
															border:false,
															items:[{
																fieldLabel: 'Id factura',
																id:'id-factura',
																name: 'FK_FACTURI',
																anchor: '90%',
																readOnly:true
															},{
																fieldLabel: 'Numar factura',
																id:'numar-factura',
																name: 'numar',
																anchor: '90%',
																readOnly:true
															},new Ext.form.ComboBox({
																anchor		:'90%',	
																fieldLabel	:'Modalitate de plata',
																name		:'n-tip-incasare', 
																allowBlank	:false, 
																blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',
																editable	:false,								
																lazyRender	:true,
																store		:new Ext.data.Store({
																			     id			:'tip_plata_ds',
																				 baseParams	:{saferequest:true,code:'pay_mode'},
																			     proxy		:new Ext.data.HttpProxy({
																			     				url		:'common/getReference/' + Math.random()
																			 }),
																 reader		: new Ext.data.JsonReader({
																						        root	:'DS_PAY_MODE',
																						        id		:'value',
																						        fields	:['value', 'option']
																	         })
															}),
															hiddenName		:'modalitate',
															displayField	:'option',
															valueField		:'value',									
															triggerAction	:'all',
															emptyText		:'[Selectati tipul]',
															listeners		: {
																		'select': function(combo, record, index) {
																			if (this.getRawValue() == 'Cash') {
																				Ext.getCmp('data-cash').reset();
																				Ext.getCmp('data-cash').enable();
																				Ext.getCmp('incasare-cash').expand();															
																				Ext.getCmp('data-ordin').reset();
																				Ext.getCmp('data-ordin').disable();
																				Ext.getCmp('numar-ordin').reset();
																				Ext.getCmp('numar-ordin').disable();																
																				Ext.getCmp('incasare-ordin').collapse();
																			} else if (this.getRawValue() == 'Ordin de plata'){
																				Ext.getCmp('data-ordin').reset();
																				Ext.getCmp('data-ordin').enable();
																				Ext.getCmp('numar-ordin').reset();
																				Ext.getCmp('numar-ordin').enable();
																				Ext.getCmp('incasare-ordin').expand();																
																				Ext.getCmp('data-cash').reset();
																				Ext.getCmp('data-cash').disable();
																				Ext.getCmp('incasare-cash').collapse();															
																			}
																		}
															}
															}),new Ext.form.NumberField({
																       	allowBlank	:false,
																		blankText	:'Reguli validare <br /><i>Camp obligatoriu</i>',
																		fieldLabel	:'Valoarea',
																		id			:'id-valoarea',		
																		name		:'valoarea',
																		anchor		:'90%'																	   
															})
														]							
														},{
												            columnWidth:0.5,
															defaultType: 'textfield',
												            layout: 'form',
															border:false,
															items:[new Ext.form.FieldSet({
																			id				:'incasare-ordin',
																			anchor			:'90%',
																            title			:'Incasare ordin de plata',
																            autoHeight		:true,
																            collapsible		:true,
																            defaultType		:'textfield',
																			items			:[new Ext.form.DateField({
																								id			:'data-ordin',	
																								anchor		:'90%',
																	                        	fieldLabel	:'Data',
																	                        	name		:'data_ordin',
																	                        	width		:190,
																								allowBlank	:false,	
																								readOnly 	:true,
																								disabled	:true,
																								invalidText :'{value} nu este o data valida - Formatul corect este: aaaa-ll-zz',
																								blankText	:'Reguli validare <br /><i>Camp obligatoriu</i><br /><i>Format: aaaa-ll-zz</i>',
																								format		:'Y-m-d'
												                    						}),{
																							        allowBlank	: false,
																									fieldLabel	:'Numar',
																									id			:'numar-ordin',
																									name		:'nr_ordin',
																									anchor		:'90%',
																									disabled	:true																	   
																							   }]
																	}),new Ext.form.FieldSet({
																			id				:'incasare-cash',
																			anchor			:'90%',
																            title			:'Incasare cash',
																            autoHeight		:true,
																            collapsible		:true,
																            defaultType		:'textfield',	
																			items			:[new Ext.form.DateField({
																								id			:'data-cash',
																								anchor		:'90%',
																	                        	fieldLabel	:'Data',
																	                        	name		:'data',
																	                        	width		:190,
																								allowBlank	:false,
																								readOnly 	:true,
																								disabled	:true,
																								invalidText :'{value} nu este o data valida - Formatul corect este: aaaa-ll-zz',
																								blankText	:'Reguli validare <br /><i>Camp obligatoriu</i><br /><i>Format: aaaa-ll-zz</i>',
																								format		:'Y-m-d'
												                    						})
																			]																																
																	})						
															]							
														}
												],
												buttons :[{
													text:'Save and close',
													tooltip	:'Salvati si Inchideti',
													formBind:true,
													handler: function(){
							        						fp_w_user_rapoarte_facturi_emise_incasare.getForm().submit({
														  		url: "user/functionalitati/incasare/" + Math.random(),
																params:{saferequest:true,table:'incasari',cyDep:false},
														  		waitTitle: 'Connecting',
														  		waitMsg: 'Validating and saving data...',										
																success:function(form, action, o) {
																	if(action.result.code == 0){
																			Ext.MessageBox.alert('Atentie:', 'Eroare la adaugare');
																	}else if(action.result.code == 1){
																		if (action.result.id) {
																			var w_print = new Ext.Window({
																				id: 'window-print-' + Math.random(),
																				width: 900,
																				height: 480,
																				layout: 'fit',
																				frame: true,
																				loadMask: {
																					msg: 'Loading...'
																				},
																				waitMsg: 'Loading',
																				modal: true,
																				closable: true,
																				closeAction: 'hide',
																				defaultType: 'iframepanel',
																				items: {
																					title: 'Tiparire Chitanta',
																					autoLoad: {
																						url: 'user/functionalitati/chitanta/' + Math.random(),
																						method: 'post',
																						params: {
																							saferequest: true,
																							ID: action.result.id
																						}
																					},
																					loadMask: true,
																					frameConfig: {
																						id: 'printIframe'
																					},
																					listeners: {
																						 domready :function(frame){
																							 frame.print();
																							 w_print.hide();
																						 }
																					}
																				}	
							
																			});
																			
																			//show print window
																			w_print.show();
																			
																			//reset form window
																			fp_w_user_rapoarte_facturi_emise_incasare.getForm().reset();
																			
																			//close form window
																			w_user_rapoarte_facturi_emise_incasare.hide();
																			
																			//reloading grid
																			ds_facturi_neincasate.reload();
																			Ext.MessageBox.alert('Mesaj:', 'Adaugare efectuata cu succes!');								
																		} else {
																			//reset form window
																			fp_w_user_rapoarte_facturi_emise_incasare.getForm().reset();
																			
																			//close form window
																			w_user_rapoarte_facturi_emise_incasare.hide();
																			
																			//reloading grid
																			ds_facturi_neincasate.reload();
																			Ext.MessageBox.alert('Mesaj:', 'Adaugare efectuata cu succes!');													
																		}
																	}else if(action.result.code == 2){
																			Ext.MessageBox.alert('Eroare la adaugare:', 'Tranzactie nereusita!');
																	}else if(action.result.code == 3){
																			Ext.MessageBox.alert('Eroare la adaugare:', 'Adaugare incasare nereusita!');
																	}else if(action.result.code == 4){
																			Ext.MessageBox.alert('Eroare la adaugare:', 'Actualizare counter chitante nereusita!');
																	}
																},										
																failure: function(form, action, o){
												                            if(action.failureType == 'server'){
												                                Ext.Msg.alert('Warning', 'Cannot save to database!', obj.errors.reason);
												                            }else{
												                                Ext.Msg.alert('Warning!', 'Authentication server is unreachable!');
												                            }
																}
							
													  	})						
													}	
												}]
											});					
									
									// end adaugare incasare form panel	-------------------------------------------------
									//-----------------------------------------------------------------------------------	
																		
										w_user_rapoarte_facturi_emise_incasare = new Ext.Window({
											id				:'w-user-rapoarte-facturi-emise-incasare' + Math.random(),
											title			:'Adaugare incasare',
											animateTarget	:'b-pay',
											width			:610,
											height			:400,
											plain			:true,
											layout			:'fit',
											modal			:true,
											closeAction		:'hide',
											items			:fp_w_user_rapoarte_facturi_emise_incasare,
											loadMask		:{msg:'Loading...'},
											listeners		:{
												show: function(){
													var selection = grid_user_rapoarte_facturi_neincasate.selModel.getSelections();
													Ext.getDom('id-factura').value = selection[0].id;
													Ext.getDom('numar-factura').value = selection[0].json.numar;
													Ext.getDom('id-valoarea').value = selection[0].json.sold;
												}
											},								
								            buttons: [{
											    text		:'Cancel',
												tooltip		:'Renuntati',
											    handler		:function(){
													fp_w_user_rapoarte_facturi_emise_incasare.getForm().reset();
											        w_user_rapoarte_facturi_emise_incasare.hide();
											    }
											}]
									
										});								
							
						}else {}
						w_user_rapoarte_facturi_emise_incasare.show();	
					
					}
				});
			} else {
			  	Ext.MessageBox.alert('Warning','Pentru a adauga o incasare, selectati doar o inregistrare!');
			}						
	}	 	

/**
 * grid
 * ************************************************************************
 */	
		function rdr_dtp(val){
			if (val < 0){
				return "<span style='color:red;'>" + val + " &laquo;</span>";
			} else if(val == 0){
				return "<span style='color:blue;'>" + val + " &lsaquo;&rsaquo;</span>";
			} else if(val > 0){
				return "<span style='color:green;'>&raquo;" + val + "</span>";
			}
		}	
					
	    ds_facturi_neincasate = new Ext.data.Store({
			id			:'table_ds_facturi_neincasate',
	        remoteSort	:true,
			baseParams	:{saferequest:true,table:'facturi_neincasate',cyDep:true},			
	        proxy: new Ext.data.HttpProxy({
	            url: 'common/getNotPayedBillsTable/' + Math.random()		
	        }),
	        reader: new Ext.data.JsonReader({
	            root: 'DS_FACTURI_NEINCASATE',
	            totalProperty: 'totalCount',
	            id: 'ID',
	            fields: [
	                'numar', 'client', 'data_emiterii', 'data_scadentei', 'overdue', 'moneda', 'facturat', 'incasat', 'sold'
	            ]
	        })
	    });	

		ds_facturi_neincasate.setDefaultSort('numar', 'desc');
	    ds_facturi_neincasate.load({params:{start:0, limit:22}});
		
		sm_facturi_neincasate = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
					
	    cm_facturi_neincasate = new Ext.grid.ColumnModel([sm_facturi_neincasate,
				{header: "Numar",				dataIndex: 'numar'},
				{header: "Client",				dataIndex: 'client'},
				{header: "Data emiterii",		dataIndex: 'data_emiterii'},
				{header: "Data scadentei",		dataIndex: 'data_scadentei'},
				{header: "DTP",					dataIndex: 'overdue',	renderer:rdr_dtp},
				{header: "Moneda",				dataIndex: 'moneda'},
				{header: "Facturat",			dataIndex: 'facturat'},
				{header: "Incasat",				dataIndex: 'incasat'},	
				{header: "Sold",				dataIndex: 'sold'}		
		]);
		
    	cm_facturi_neincasate.defaultSortable = true;	
		
	    grid_user_rapoarte_facturi_neincasate = new Ext.grid.GridPanel({
			id:'gridfacturineincasate-' + Math.random(),
	        renderTo:'user_rapoarte_facturi_neincasate',
			height:569,
			anchor:'100%',	
			frame:false,					
	        title:'<?=$title?>',
	        store: ds_facturi_neincasate,
	        cm: cm_facturi_neincasate,
	        loadMask: true,
	        viewConfig: {
	            forceFit:true							
	        },
	        tbar:[{
					id		:'b-pay',
		            text	:'Incaseaza',
		            tooltip	:'Incaseaza',
		            iconCls	:'b_pay_cls',
					handler	:facturi_pay
	        	},'-',getExcel()
			],		
	        bbar: new Ext.PagingToolbar({
				beforePageText:'Pagina&nbsp;',
				afterPageText:'din {0}',
				firstText:'Prima pagina',
				lastText:'Ultima pagina',
				nextText:'Pagina urmatoare',
				prevText:'Pagina precedenta',   
	            pageSize: 22,
	            store: ds_facturi_neincasate,
	            displayInfo: true,
	            displayMsg: 'Facturi neincasate {0} - {1} din {2}',
	            emptyMsg: "No records",
				plugins: new Ext.ux.Andrie.pPageSize({
					  beforeText:'',		
				      afterText: '&nbsp;inreg/pagina',
				      comboCfg: {width: 50}
				      })
			}),plugins: new Ext.ux.grid.Search({
						searchText:'Criterii',
						searchTipText:'Introduceti textul dorit...',
						iconCls:'b_search_cls',
						minChars:2,
						autoFocus:true,
						text:'Cauta dupa camp',
						mode:'remote',
						position:'top'
			})
		});		

	//end on document ready
	});
</script>
